import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/simple_choice_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/department_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/tool_list_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_work_all/common_work_all_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

class HoistingJobApplicationController extends GetxController {
//作业总页面controller
  final workAllPageController = Get.find<CommonWorkAllController>();

  //作业申请实体
  ExecuteTicketReceiptList executeTicketReceipt = ExecuteTicketReceiptList();

  //司索人
  ExecuteTicketReceiptListOperatorLists rope = ExecuteTicketReceiptListOperatorLists();

  //指挥人
  ExecuteTicketReceiptListOperatorLists command = ExecuteTicketReceiptListOperatorLists();

  //监护人
  ExecuteTicketReceiptListOperatorLists guardian = ExecuteTicketReceiptListOperatorLists();

  // 工具集选择列表
  List<ToolListEntity> toolList = [];

  // 工具集选中选择列表
  List<ToolListEntity> toolListChecked = [];

  @override
  void onInit() {
    super.onInit();
    //初始化页面列表
    initData();
  }

  ///初始化数据
  initData() async {
    //获取数据作业申请数据
    final res = await HttpUtil().generateGetRequest<ExecuteTicketReceiptList>(Interface.getTicketReceiptDetail,
        queryParameters: {'ticketReceiptId': workAllPageController.executeEntity.ticketReceiptId}).execute();
    res.onSuccess((result) {
      workAllPageController.executeEntity.ticketReceiptList = result.data;
    });
    //赋值
    executeTicketReceipt = workAllPageController.executeEntity.ticketReceiptList!;
    // 查找已选中的吊具

    //查找已选中的人员
    for (var item in executeTicketReceipt.operatorLists!) {
      //司索人
      if (item.operatorType == 4) {
        rope = item;
      }
      //指挥人
      if (item.operatorType == 5) {
        command = item;
      }
      //监护人
      if (item.operatorType == 2) {
        guardian = item;
      }
    }
    update();
    queryJobToolList();
  }

  /// 获取作业工具列表
  void queryJobToolList() async {
    final specialJobType = DictDataInfo.specialJobType;
    String workTypeId = '';
    //查询吊装作业类型id
    for (var item in specialJobType) {
      if (item.dictionaryLabel == '吊装作业') {
        workTypeId = item.id!;
        break;
      }
    }
    final data = {
      'keyWords': '', // 关键词
      'workTypeId': workTypeId, // 作业类型id
      'identificationIds': [],
    };
    //查询吊装作业工具列表
    final res = await HttpUtil()
        .generateGetRequest<List<ToolListEntity>>(
          Interface.jobToolListUrl,
          queryParameters: data,
        )
        .execute();

    res.onSuccess((result) {
      toolList = result.data ?? [];
      update();
    });
  }

  /// 吊具名称选择
  void showSpreader() {
    CustomSelectFunction.selectMultipleBottomSheet<ToolListEntity>(
      title: '吊具选择',
      dataList: toolList,
      checkedList: toolListChecked,
      onCallBack: (value) {
        toolListChecked = value;
        //逗号隔开
        executeTicketReceipt.workOtherDataDTO!.slingName = toolListChecked.map((e) => e.workTool).join(',');
        update();
      },
    );
  }

  ///作业申请时间选择
  void showDatePicker() {
    CustomSelectFunction.selectDateTime(onCallBack: (String value) {
      executeTicketReceipt.applyDate = value;
      update();
    });
  }

  ///作业单位选取
  void applyUnitSelect() {
    Get.toNamed(AppRoutes.unitSelection, arguments: {
      'queryParameters': {'type': 2},
      'isRadio': true,
    })?.then((value) {
      //如果不为空则设置单位信息
      if (value != null) {
        value as List<DepartmentEntity>;
        executeTicketReceipt.workDepartmentName = value[0].getShowName();
        executeTicketReceipt.workDepartmentId = value[0].getId();
        executeTicketReceipt.workDepartmentType = value[0].workDepartmentType;
      }
      update();
    });
  }

  /// 选择质量及作业级别
  void selectQualityAndLevel() {
    // CustomBottomSheet<String>(
    //   dataList: const ['一级吊装作业：m>100t', '二级吊装作业：40t≤m≤100t', '三级吊装作业：m<40t'],
    //   onConfirm: (value) {
    //     executeTicketReceipt.workOtherDataDTO!.slingWeight = value;
    //     update();
    //   },
    // ).showBottomSheetDialog();

    CustomSelectFunction.selectMultipleBottomSheet<SimpleChoiceBean>(
      title: '质量及级别选择',
      dataList: [
        SimpleChoiceBean(id: '1', name: '一级吊装作业：m>100t'),
        SimpleChoiceBean(id: '2', name: '二级吊装作业：40t≤m≤100t'),
        SimpleChoiceBean(id: '3', name: '三级吊装作业：m<40t'),
      ],
      checkedList: [],
      isMultiple: false,
      onCallBack: (value) {
        executeTicketReceipt.workOtherDataDTO!.slingWeight = value[0].name;
        update();
      },
    );
  }

  /// 作业地点选取
  void locationSelect() {
    Get.toNamed(AppRoutes.planSelectedLocation)?.then((value) {
      if (value != null && value is Map) {
        final Map<String, double> laAndLon = value['laAndLon'] as Map<String, double>;
        final String ticketAddress = value['ticketAddress'] as String;
        executeTicketReceipt.workOtherDataDTO!.longitude = laAndLon['longitude'];
        executeTicketReceipt.workOtherDataDTO!.latitude = laAndLon['latitude'];
        executeTicketReceipt.workOtherDataDTO!.otherTicketAddress = ticketAddress;
        update();
      }
    });
  }
}
